package com.xcj.springai.node;

import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.StateGraph;
import com.alibaba.cloud.ai.graph.action.NodeAction;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 人类反馈处理节点，用于判断用户是否满意或希望继续处理流程（如翻译等）。
 */
@Slf4j
@Component
public class HumanFeedbackNode implements NodeAction {

    private static final Logger logger = LoggerFactory.getLogger(HumanFeedbackNode.class);

    /**
     * 执行节点动作的方法。
     * 根据状态中的 human feedback 判断下一步跳转的节点，并写入状态值供条件边使用。
     *
     * @param state 当前图的整体状态对象，包含上下文数据及反馈信息。
     * @return 返回一个 Map（状态更新），包含 "humannextnode"，供 HumanFeedbackDispatcher 判断跳转使用。
     */
    @Override
    public Map<String, Object> apply(OverAllState state) {


        logger.info("HumanFeedbackNode节点 humanfeedback node is running.");
        logger.info("HumanFeedbackNode节点 In node: data = {}", state.data());
        logger.info("HumanFeedbackNode节点 State object hash: {}", System.identityHashCode(state));
        logger.info("HumanFeedbackNode节点 Received human feedback in node: {}", state.humanFeedback());
        logger.info("HumanFeedbackNode节点 In node: humanFeedback = {}", state.humanFeedback());
        logger.info("HumanFeedbackNode节点 Before stream: humanFeedback = {}", state.data().get("humanfeedback"));

        // 创建返回结果的 Map，用于存放状态更新humanFeedback = null
        HashMap<String, Object> resultMap = new HashMap<>();
        String nextStep = StateGraph.END;

        OverAllState.HumanFeedback humanFeedback = state.humanFeedback();

        if (humanFeedback != null && humanFeedback.data() != null) {

            Map<String, Object> feedBackData = humanFeedback.data();


            Object feedbackObj = feedBackData.getOrDefault("feedback", true);
            boolean feedback = Boolean.parseBoolean(feedbackObj.toString());

            // 如果反馈为 true，说明用户希望继续处理，跳转到 translate 节点
            if (feedback) {
                nextStep = "translate";
            }else {
                nextStep = "summary";
            }

        } else {
            logger.warn("No human feedback data found, defaulting to continue.");
            nextStep = "translate";
        }

        // 将判断出的下一步节点写入状态字段 "humannextnode"
        resultMap.put("humannextnode", nextStep);
        logger.info("humanfeedback node -> {} node", nextStep);

        // 返回结果 Map，供图系统用于更新状态
        return resultMap;
    }


}


